package com.adams.app.ui.adapter;

import com.adams.app.R;
import com.adams.app.data.RequestManager;
import com.adams.app.model.Specialty;
import com.adams.app.vendor.HappyGyApi;
import com.android.volley.toolbox.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Created by Issac on 7/18/13.
 */
public class SpecialtyAdapter extends CursorAdapter {
	private LayoutInflater mLayoutInflater;

	private ListView mListView;

	private Drawable mDefaultImageDrawable;

	public SpecialtyAdapter(Context context, ListView listView) {
		super(context, null, false);
		mLayoutInflater = ((Activity) context).getLayoutInflater();
		mListView = listView;
		mDefaultImageDrawable = context.getResources().getDrawable(R.drawable.travel_bg);
	}

	@Override
	public Specialty getItem(int position) {
		mCursor.moveToPosition(position);
		return Specialty.fromCursor(mCursor);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
		return mLayoutInflater.inflate(R.layout.listitem_specialty, null);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		Holder holder = getHolder(view);
		if (holder.imageRequest != null) {
			holder.imageRequest.cancelRequest();
		}

		view.setEnabled(!mListView.isItemChecked(cursor.getPosition()
				+ mListView.getHeaderViewsCount()));

		Specialty specialty = Specialty.fromCursor(cursor);
		holder.imageRequest = RequestManager.loadImage(HappyGyApi.BASE_URL
				+ specialty.getPicture(), RequestManager.getImageListener(
				holder.image, mDefaultImageDrawable, mDefaultImageDrawable));
		holder.name.setText(specialty.getName());
	}

	private Holder getHolder(final View view) {
		Holder holder = (Holder) view.getTag();
		if (holder == null) {
			holder = new Holder(view);
			view.setTag(holder);
		}
		return holder;
	}

	private class Holder {
		public ImageView image;

		public TextView name;

		public ImageLoader.ImageContainer imageRequest;

		public Holder(View view) {
			image = (ImageView) view.findViewById(R.id.image);
			name = (TextView) view.findViewById(R.id.name);
		}
	}
}
